package com.auto.video.tv;

import static com.xin.auto.lib.base.Contants.MONTH_ITEMS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.serialport.SerialPortFinder;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;

import com.auto.tv.serial.comn.Device;
import com.auto.tv.serial.comn.SerialPortManager;
import com.auto.tv.serial.comn.constant.FlagManager;
import com.auto.tv.serial.comn.constant.PreferenceKeys;
import com.auto.tv.serial.comn.message.RecvMessage;
import com.auto.tv.serial.comn.utils.CustomByteUtil;
import com.auto.tv.serial.comn.utils.PrefHelper;
import com.auto.video.tv.presenter.IVideoPresenter;
import com.auto.video.tv.presenter.VideoPresenter;
import com.auto.video.tv.widget.WeatherItemView;
import com.xin.auto.lib.base.CalendarUtils;
import com.xin.auto.lib.base.CommonUtils;
import com.xin.auto.lib.base.CustomTextWatcher;
import com.xin.auto.lib.base.DateUtils;
import com.xin.auto.lib.base.DbHelper;
import com.xin.auto.lib.base.ExcelUtil;
import com.xin.auto.lib.base.Humans;
import com.xin.auto.lib.base.SharedPreferencesUtils;
import com.xin.auto.lib.base.UsbHelper;
import com.xin.auto.lib.base.adloopvideoplayer.service.UsbService;
import com.xin.auto.lib.base.adloopvideoplayer.utils.ConstantUtil;
import com.xin.auto.lib.base.adloopvideoplayer.utils.UsbImpl;
import com.xin.auto.lib.base.adloopvideoplayer.view.IView;
import com.yanzhenjie.permission.AndPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.jahnen.libaums.core.fs.UsbFile;

public class MainActivity extends FragmentActivity implements View.OnClickListener,
        MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, IView, AdapterView.OnItemSelectedListener, MediaPlayer.OnPreparedListener {
    private static final String TAG = "MainActivity";
    private List<String> mMediaList = new ArrayList<>();

    private VideoView mVideoView;
    private ImageButton mImageButton;
    private LinearLayout mPeopleLayout;
    private Button mConfirmBtn;
    private Button mSaveExcel;

    private TextView mCurrentTextView;
    private TextView mMonthTextView;
    private Spinner mSpinner;
    private Spinner mSpinnerDevPath;
    private String mSelectMonth = "0";
    private LinearLayout mConfirmLayout;

    private WeatherItemView mTemperature;
    private WeatherItemView mHumidity;
    private WeatherItemView mNGas;
    private WeatherItemView mHsGas;
    private WeatherItemView mIllumination;
    private LinearLayout mValidateLayout;

    // 人流量
    private int traffic = 0;
    // 温度
    private String temperature = "";
    // 湿度
    private String humidity = "";
    // 氨气
    private String ammonia = "";
    // 硫化氢
    private String hydrogen_sulfide = "";
    // 光照
    private String illumination = "";

    // 设置信息
    private boolean setInfoFlag = false;
    // 升级模式
    private boolean updateModeFlag = false;
    //收到升级包
    private boolean receiveDataFlag = false;

    private byte[] recvBuf = new byte[1024];

    private static final int RECEIVER_DATA = 0x100;
    private static final int REFRESH_HUMANS_DATA = 0x101;

    private IVideoPresenter mPresenter;

    private String mSerialPath = "/dev/ttyS3";
    private Device mDevice;

    private int mDeviceIndex;
    private int mBaudrateIndex;

    private String[] mDevices;

    private boolean mOpened = false;
    private UsbHelper mUsbHelper;
    private DbHelper dbHelper;
    private boolean isEditMode;

    private int intervalTime = 900;
    private boolean isStartHeart = false;
    private int mediaIndex = -1;
    private int tempHumans = 0;
    private int serialNum = 255;
    private int currentMonth;
    private String currentYear;
    private Button mPwdConfirm;
    private EditText mPwdEdit;

    private SharedPreferencesUtils sharedPreferencesUtils;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == RECEIVER_DATA) {
                mCurrentTextView.setText(getString(R.string.app_current_peoples, String.valueOf(traffic)));
                mTemperature.setValueText(String.valueOf(temperature));
                mHumidity.setValueText(String.valueOf(humidity));
                mNGas.setValueText(String.valueOf(ammonia));
                mHsGas.setValueText(String.valueOf(hydrogen_sulfide));
                mIllumination.setValueText(String.valueOf(illumination));
            } else if (msg.what == REFRESH_HUMANS_DATA) {
                int humans = dbHelper.selectMonthValue(CalendarUtils.getMonth());
                mMonthTextView.setText(String.valueOf(humans));
            }
            return false;
        }
    });

    @SuppressLint("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate!");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        mPresenter = new VideoPresenter(this);
        EventBus.getDefault().register(this);
        dbHelper = new DbHelper(this);

        sharedPreferencesUtils = SharedPreferencesUtils.init(MainActivity.this);
        mSerialPath = sharedPreferencesUtils.getString(CommonUtils.SERIES_PATH, "/dev/ttyS3");
        Log.i(TAG, "mSerialPath ->>" + mSerialPath);

        currentYear = CalendarUtils.getYear();
        Intent service = new Intent(this, UsbService.class);
        startService(service);

        mUsbHelper = new UsbHelper(this, new UsbImpl() {
            @Override
            public void insertUsb(UsbDevice device_add) {
                Log.d(TAG, "insertUsb");
            }
        });
        initDevice();
        initView();

        initPermission();
        initMediaPlayer();
        openSeriesPort();
        switchSettingMode(false);

        String userCode = dbHelper.selectValidateCode();
        if (TextUtils.isEmpty(userCode) || !"jy20220227@310".equals(userCode)) {
            mValidateLayout.setVisibility(View.VISIBLE);
        } else {
            mValidateLayout.setVisibility(View.GONE);
        }
    }

    @SuppressLint("WrongConstant")
    private void initPermission() {
        AndPermission.with(this)
                .runtime()
                .permission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.INTERNET)
                .onGranted(permissions -> {
                    mPresenter.getData(mUsbHelper);
                })
                .onDenied(permissions -> {
                    Toast.makeText(this, "没获取到sd卡权限，无法播放本地视频哦", Toast.LENGTH_LONG).show();
                })
                .start();
    }

    /**
     * 初始化设备列表
     */
    private void initDevice() {
        SerialPortFinder serialPortFinder = new SerialPortFinder();

        // 设备
        mDevices = serialPortFinder.getAllDevicesPath();
        Log.i(TAG, "mDevices->>" + mDevices.length);
        if (mDevices.length == 0) {
            mDevices = new String[]{
                    getString(R.string.no_serial_device)
            };
        }

        mDeviceIndex = PrefHelper.getDefault().getInt(PreferenceKeys.SERIAL_PORT_DEVICES, 0);
        mDeviceIndex = mDeviceIndex >= mDevices.length ? mDevices.length - 1 : mDeviceIndex;
        mBaudrateIndex = PrefHelper.getDefault().getInt(PreferenceKeys.BAUD_RATE, 0);
        mDevice = new Device(mSerialPath, "115200");
    }

    private boolean isSendFirst = false;

    /**
     * 打开或关闭串口
     */
    private void openSeriesPort() {
        // 保存配置
        PrefHelper.getDefault().saveInt(PreferenceKeys.SERIAL_PORT_DEVICES, mDeviceIndex);
        PrefHelper.getDefault().saveInt(PreferenceKeys.BAUD_RATE, mBaudrateIndex);

        mOpened = SerialPortManager.instance().open(mDevice) != null;
        Log.d(TAG, "mOpen ->>" + mOpened);
        if (mOpened) {
            if (!isSendFirst) {
                String timeString = CustomByteUtil.hexTimeString();
                SerialPortManager.instance().sendCommand(FlagManager.SEND_HEARTBEAT, "01" + timeString);
                isSendFirst = true;
            }
        } else {
            isSendFirst = false;
        }
    }

    public void heartBeatCheck() {
        String timeString = CustomByteUtil.hexTimeString();
        SerialPortManager.instance().sendCommand(FlagManager.SEND_HEARTBEAT, "02" + timeString);
        Log.d(TAG, "回复消息：" + "02" + timeString);
    }

    @SuppressLint("StringFormatInvalid")
    private void initView() {
        mVideoView = findViewById(R.id.video_view);
        mTemperature = findViewById(R.id.temperature);
        mHumidity = findViewById(R.id.humidity);
        mNGas = findViewById(R.id.n_gas);
        mHsGas = findViewById(R.id.hs_gas);
        mIllumination = findViewById(R.id.illumination);
        mConfirmLayout = findViewById(R.id.btn_confirm);
        mSpinnerDevPath = findViewById(R.id.dev_path);
        mValidateLayout = findViewById(R.id.validate_layout);
        mPwdConfirm = findViewById(R.id.pwd_confirm);
        mPwdConfirm.setOnClickListener(this);
        mPwdEdit = findViewById(R.id.pwd_validate);
        mPwdEdit.addTextChangedListener(new CustomTextWatcher() {

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        ArrayAdapter<String> deviceAdapter =
                new ArrayAdapter<>(this, R.layout.spinner_default_item, mDevices);
        deviceAdapter.setDropDownViewResource(R.layout.spinner_item);
        mSpinnerDevPath.setAdapter(deviceAdapter);
        mSpinnerDevPath.setOnItemSelectedListener(this);

        mPeopleLayout = findViewById(R.id.peoples_layout);
        mSaveExcel = findViewById(R.id.save_excel);
        mSaveExcel.setOnClickListener(this);
        mConfirmBtn = findViewById(R.id.setting_confirm);
        mConfirmBtn.setOnClickListener(this);
        mCurrentTextView = findViewById(R.id.current_peoples_num);
        traffic = dbHelper.selectMonthValue(-1);
        Log.i(TAG, "current->>" + traffic);
        mCurrentTextView.setText(getString(R.string.app_current_peoples, String.valueOf(traffic)));
        // 月人流量
        mMonthTextView = findViewById(R.id.month_peoples);
        currentMonth = CalendarUtils.getMonth();
        int humans = dbHelper.selectMonthValue(currentMonth);
        Log.i(TAG, "month humans->>" + humans);

        mMonthTextView.setText(getString(R.string.app_current_peoples, String.valueOf(humans)));

        mImageButton = findViewById(R.id.weather_setting);
        mImageButton.setOnClickListener(this);

        mSpinner = findViewById(R.id.select_peoples_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, MONTH_ITEMS);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(adapter);
        mSpinner.setSelection(DateUtils.getMonth() - 1);
        mSelectMonth = String.valueOf(CalendarUtils.getMonth());
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mSelectMonth = MONTH_ITEMS[i];
                Log.d(TAG, "mSpinner onItemSelected" + i + ", " + mSelectMonth);
                int monthHumans = dbHelper.selectMonthValue(Integer.parseInt(mSelectMonth));
                mMonthTextView.setText(String.valueOf(monthHumans));
                mHandler.sendEmptyMessageDelayed(REFRESH_HUMANS_DATA, 10 * 1000 * 60);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void setEditable(Boolean isEditable) {
        mTemperature.setEditable(isEditable);
        mTemperature.requestViewFocus();
        mHumidity.setEditable(isEditable);
        mNGas.setEditable(isEditable);
        mHsGas.setEditable(isEditable);
        mIllumination.setEditable(isEditable);
        isEditMode = isEditable;
    }

    private void initMediaPlayer() {
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume!!!");
        if (mVideoView != null && !mVideoView.isPlaying() && mMediaList.size() > 0) {
            Log.d(TAG, "onResume ->>" + mVideoView.isPlaying());
            mVideoView.start();
        }
        Log.d(TAG, "onResume closed->>" + SerialPortManager.instance().isClosed());
        if (SerialPortManager.instance().isClosed()) {
            openSeriesPort();
        }
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
        if (mVideoView.isPlaying()) {
            mVideoView.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.weather_setting) {
            setEditable(true);
            switchSettingMode(true);
        } else if (viewId == R.id.setting_confirm) {
            if (!TextUtils.isEmpty(mSerialPath)) {
                sharedPreferencesUtils.putString(CommonUtils.SERIES_PATH, mSerialPath);
                openSeriesPort();
            }

            temperature = mTemperature.getText();
            humidity = mHumidity.getText();
            ammonia = mNGas.getText();
            hydrogen_sulfide = mHsGas.getText();
            illumination = mIllumination.getText();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SerialPortManager.instance().sendSetInfo(ConstantUtil.strToFloat(temperature),
                            ConstantUtil.strToFloat(humidity),
                            ConstantUtil.strToFloat(ammonia),
                            ConstantUtil.strToFloat(hydrogen_sulfide),
                            ConstantUtil.strToFloat(illumination));
                }
            }).start();

            setEditable(false);
            switchSettingMode(false);
        } else if (viewId == R.id.save_excel) {
            saveExcel();
            setEditable(false);
            switchSettingMode(false);
        } else if (viewId == R.id.pwd_confirm) {
            String pwdStr = mPwdEdit.getText().toString();
            if (!TextUtils.isEmpty(pwdStr) && "jy20220227@310".equals(pwdStr)) {
                dbHelper.updateIfValidateExist(pwdStr);
                mValidateLayout.setVisibility(View.GONE);
            } else {
                Toast.makeText(MainActivity.this, "请输入正确的授权码!", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void switchSettingMode(boolean isConfirmMode) {
        mSpinnerDevPath.setVisibility(isConfirmMode ? View.VISIBLE : View.GONE);
        mConfirmLayout.setVisibility(isConfirmMode ? View.VISIBLE : View.GONE);
        mPeopleLayout.setVisibility(isConfirmMode ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.d(TAG, "videos onCompletion");
        if (mMediaList != null && mMediaList.size() > 0) {
            mediaIndex++;
        }
        if (mediaIndex >= mMediaList.size()) {
            mediaIndex = 0;
        }
        if (mediaIndex < 0) {
            return;
        }
        mVideoView.setVideoPath(mMediaList.get(mediaIndex));
        mVideoView.start();
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        mVideoView.setVideoPath(mMediaList.get(mediaIndex));
        mVideoView.start();
        Toast.makeText(MainActivity.this, "播放错误", Toast.LENGTH_LONG).show();
        return false;
    }

    /**
     * 用EventBus进行线程间通信，也可以使用Handler
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RecvMessage msg) {
        if (isEditMode) {
            return;
        }
        Log.i(TAG, "获取到了从传感器发送的串口数据: " + msg.getMessage());
        recvBuf = CustomByteUtil.toByteArray(msg.getMessage());
        if (recvBuf[0] == (byte) 0x10 && recvBuf[3] != (byte) (serialNum & 0xFF)) {
            heartBeatCheck();
            serialNum = recvBuf[3];
            if (recvBuf[2] == (byte) 0xA0 && recvBuf[4] == (byte) 0x15) {
                tempHumans += (recvBuf[5] & 0xFF);
                temperature = CustomByteUtil.convertDoubleToStr(((CustomByteUtil.hexByteTofloat(recvBuf[6], recvBuf[7], 100)
                        + CustomByteUtil.hexByteTofloat(recvBuf[16], recvBuf[17], 100)) * 0.5), "0.00");
                humidity = CustomByteUtil.convertDoubleToStr(((CustomByteUtil.hexByteTofloat(recvBuf[8], recvBuf[9], 100)
                        + CustomByteUtil.hexByteTofloat(recvBuf[18], recvBuf[19], 100)) * 0.5), "0.00");
                ammonia = CustomByteUtil.convertDoubleToStr(((CustomByteUtil.hexByteTofloat(recvBuf[10], recvBuf[11], 1000)
                        + CustomByteUtil.hexByteTofloat(recvBuf[20], recvBuf[21], 1000)) * 0.5), "0.000");
                hydrogen_sulfide = CustomByteUtil.convertDoubleToStr(((CustomByteUtil.hexByteTofloat(recvBuf[12], recvBuf[13], 1000)
                        + CustomByteUtil.hexByteTofloat(recvBuf[22], recvBuf[23], 1000)) * 0.5), "0.000");
                illumination = CustomByteUtil.convertDoubleToStr(((CustomByteUtil.hexByteTofloat(recvBuf[14], recvBuf[15], 1)
                        + CustomByteUtil.hexByteTofloat(recvBuf[24], recvBuf[25], 1)) * 0.5), "0");
                mHandler.removeMessages(RECEIVER_DATA);
                mHandler.sendEmptyMessage(RECEIVER_DATA);
            }
            // 设置成功
            setInfoFlag = recvBuf[2] == (byte) 0xA1 && recvBuf[5] == (byte) 0x02;
            updateModeFlag = recvBuf[2] == (byte) 0xA2 && recvBuf[5] == (byte) 0x02;
            receiveDataFlag = recvBuf[2] == (byte) 0xA3 && recvBuf[7] == (byte) 0x02;
            CommonUtils.printErrLog(recvBuf[2], recvBuf[5]);

            if (serialNum > 255) {
                serialNum = 0;
            }
        }

        if (tempHumans > 0) {
            int month = CalendarUtils.getMonth();
            if (CalendarUtils.isOClockO()) {
                Log.i(TAG, "0点，重置当前人数！" + currentMonth + ", curr->" + month);
                traffic = tempHumans;
                mCurrentTextView.setText(String.valueOf(tempHumans));
            } else {
                traffic += tempHumans;
            }
            Log.i(TAG, "month:" + month + ", curr->" + currentMonth);
            if (currentMonth < month || (currentMonth == 12 && month == 1)) {
                currentMonth = month;
                mSpinner.setSelection(currentMonth-1);
                mSelectMonth = String.valueOf(currentMonth);
            }
            currentYear = CalendarUtils.getYear();
            Humans humans = new Humans(currentYear + "13", "-1", traffic);
            dbHelper.updateIfExist(humans);

            int hisHumans = dbHelper.selectMonthValue(month);
            Humans monthHumans = new Humans(currentYear + month, String.valueOf(month), hisHumans + tempHumans);
            Log.d(TAG, "month->>" + month + ", hisHumans:" + monthHumans.getHumanNums());
            dbHelper.updateIfExist(monthHumans);

            if (Integer.parseInt(mSelectMonth) == month) {
                mMonthTextView.setText(String.valueOf(monthHumans.getHumanNums()));
            }
            tempHumans = 0;
        }

        if (CalendarUtils.isOClock()) {
            saveExcel();
        }
    }

    private Thread mSaveExcelThread;

    private void   saveExcel() {
        mSaveExcelThread = new Thread(() -> ExcelUtil.getInstance().exportExcel(getApplicationContext(),
                mUsbHelper, progress -> {
            if (progress >= 99) {
                runOnUiThread(() -> Toast.makeText(getApplicationContext(), "导出成功!", Toast.LENGTH_LONG).show());
            }
        }));
        mSaveExcelThread.start();
    }

    @Override
    protected void onDestroy() {
        mUsbHelper.finishUsbHelper();
        mSaveExcelThread = null;
        SerialPortManager.instance().close();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void showData(List<UsbFile> data) {
        if (data == null || data.size() <= 0) {
            Toast.makeText(MainActivity.this, "无法读取视频列表", Toast.LENGTH_LONG).show();
            return;
        }
        for (UsbFile usbFile : data) {
            copyUSbFile(usbFile);
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        mDeviceIndex = position;
        mSerialPath = mDevices[position];
        mDevice.setPath(mDevices[mDeviceIndex]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private String localCurrentPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

    /**
     * 复制 USB 文件到本地
     *
     * @param file USB文件
     */
    private void copyUSbFile(final UsbFile file) {
        //复制到本地的文件路径
        final String filePath = localCurrentPath + File.separator + file.getName();
        File mediaFile = new File(filePath);

        if (mediaFile.exists() && mediaFile.length() > 0) {
            mMediaList.add(filePath);
            mediaIndex = 0;
            mVideoView.setVideoPath(mMediaList.get(0));
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                deleteOtherFiles(mediaFile);
                //复制结果
                final boolean result = mUsbHelper.saveUSbFileToLocal(file, filePath, new UsbHelper.DownloadProgressListener() {
                    @Override
                    public void downloadProgress(final int progress) {

                    }
                });
                //主线程更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result) {
                            mMediaList.add(filePath);
                            mediaIndex = 0;
                            mVideoView.setVideoPath(mMediaList.get(0));

                        } else {
                            Toast.makeText(MainActivity.this, "复制失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    private void deleteOtherFiles(File mediaFile) {
        if (mediaFile != null && !TextUtils.isEmpty(mediaFile.getParent())) {
            String dir = mediaFile.getParent();
            File file = new File(dir);
            for (File child : file.listFiles()) {
                if (!TextUtils.isEmpty(child.getName()) && !child.getName().equals(mediaFile.getName())) {
                    boolean isDel = child.delete();
                    Log.d(TAG, "deleteOtherFiles: " + isDel);
                }
            }
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mediaPlayer.setOnVideoSizeChangedListener((mediaPlayer1, i, i1) -> {
            MediaController mediaController = new MediaController(MainActivity.this);
            mVideoView.setMediaController(mediaController);
            mediaController.setAnchorView(mVideoView);
        });
    }
}